package com.btpj.blog_server.controller;

import com.btpj.blog_server.entity.BaseResp;
import com.btpj.blog_server.entity.Category;
import com.btpj.blog_server.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.util.List;

@RestController
@RequestMapping("/admin/category")
public class CategoryController {

    @Autowired
    CategoryService categoryService;

    @GetMapping("/all")
    public BaseResp<List<Category>> getAllCategories() {
        return new BaseResp<>(0, "请求成功", categoryService.getAllCategories());
    }

    @PostMapping("/add")
    public BaseResp<Void> addCategory(String name) {
        if (name == null || name.isEmpty()) {
            return new BaseResp<>(1, "栏目名称不能为空");
        }
        if (categoryService.getCategoryByName(name) != null) {
            return new BaseResp<>(1, "栏目名称已存在，无需重复添加");
        }
        Category category = new Category();
        category.setCreateDate(new Timestamp(System.currentTimeMillis()));
        category.setName(name);
        if (categoryService.addCategory(category)) {
            return new BaseResp<>(0, "栏目添加成功");
        } else {
            return new BaseResp<>(1, "栏目添加失败");
        }
    }

    /**
     * 删除栏目
     *
     * @param ids 栏目ID，可多个，多个以,隔开
     * @return BaseResp
     */
    @DeleteMapping("/deleteIds")
    public BaseResp<Void> deleteCategories(String ids) {
        if (categoryService.deleteCategories(ids)) {
            return new BaseResp<>(0, "批量删除成功");
        } else {
            return new BaseResp<>(1, "批量删除失败");
        }
    }

    /**
     * 更新栏目
     *
     * @param category 栏目
     * @return BaseResp
     */
    @PostMapping("/update")
    public BaseResp<Void> updateCategory(Category category) {
        if (categoryService.updateCategory(category)) {
            return new BaseResp<>(0, "栏目修改成功");
        } else {
            return new BaseResp<>(1, "栏目修改失败");
        }
    }
}
